/<template>
  <div>
    <h3>购物车</h3>
    <ul>
      <li
        v-for="(item, index) in $store.state.list"
        :key="item.id"
        class="item"
      >
        <input
          type="checkbox"
          v-model="item.isCheck"
          @click="changeCheck(index)"
        />
        <img :src="item.img" alt="" />
        <div>
          <h3>{{ item.title }}</h3>
          <p>{{ item.price }}元</p>
          <div>
            <button
              :disabled="item.num <= 1"
              @click="$store.commit('reduceNum', index)"
            >
              -
            </button>
            <span>{{ item.num }}</span>
            <button @click="$store.commit('addNum', index)">+</button>
          </div>
        </div>
      </li>
    </ul>
    <div class="foot">
      <input type="checkbox" v-model="allCheck" @click="changeAll" />
      <label>全选</label>
      <b>总价:{{ totalPrice }}</b>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  data() {
    return {
      allCheck: false,
      totalPrice: 0,
    };
  },
  // 计算属性
  computed: {
    ...mapState(["list"]),
  },
  mounted() {
    this.$store.dispatch("getList");
  },
  watch: {
    list: {
      // 监听函数
      handler: function (newValue) {
        this.totalPrice = 0;
        // 计算总价
        newValue.forEach((v) => {
          if (v.isCheck) {
            this.totalPrice += v.num * v.price;
          }
        });
        // 反选
        this.allCheck = newValue.every((v) => {
          return v.isCheck;
        });
      },
      deep: true,
    },
  },
  methods: {
    changeCheck(index) {
      this.$store.commit("setCheck", index);
    },
    changeAll() {
      this.$store.commit("setAll", this.allCheck);
    },
  },
};
</script>

<style lang='scss'>
.item {
  width: 100%;
  height: 150px;
  padding: 10px;
  display: flex;
  align-items: center;
  img {
    width: 100px;
    height: 100px;
    padding: 0 10px;
  }
  button {
    width: 30px;
    height: 30px;
  }
  span {
    display: inline-block;
    width: 30px;
    text-align: center;
  }
}
</style>